<template>
  <div class="Reiki-preview">
    <section>
      <slot></slot>
    </section>
    <div class="preview-bottom">
      <span name="Code" @click="showSourceCode">
        {{ codeVisible ? "关闭代码" : "查看代码" }}
      </span>
    </div>
    <div v-show="codeVisible" class="source-code">
      <pre
        class="language-html"
      ><code class="language-html">{{ previewSourceCode }}</code></pre>
    </div>
  </div>
</template>

<script lang="ts">
import Prism from "prismjs";

import "../assets/css/prism.css";
import { defineComponent, onMounted, ref, computed, nextTick } from "vue";

export default defineComponent({
  name: "Preview",
  props: {
    /** 组件名称 */
    compName: {
      type: String,
      default: "",
      require: true,
    },
    /** 要显示代码的组件 */
    demoName: {
      type: String,
      default: "",
      require: true,
    },
  },
  setup(props) {
    const isDev: Boolean = import.meta.env.MODE === "development";
    let sourceCode = ref("");
    let codeVisible = ref(false);
    const { compName, demoName } = props;

    const previewSourceCode = computed(() => {
      return sourceCode.value.replace(/'\.\.\/\.\.\/index'/g, `'@tencent/rk'`);
    });

    function showSourceCode() {
      codeVisible.value = !codeVisible.value;
    }

    onMounted(() => {
      async function getVal() {
        if (compName && demoName) {
          if (isDev) {
            sourceCode.value = (
              await import(
                /* @vite-ignore */ `../../packages/${compName}/docs/${demoName}.vue?raw`
              )
            ).default;
          } else {
            sourceCode.value = await fetch(
              `${isDev ? "" : "/rk"}/packages/${compName}/docs/${demoName}.vue`
            ).then((res) => res.text());
          }
        }
        await nextTick();
        Prism.highlightAll();
      }
      getVal();
    });

    return {
      sourceCode,
      codeVisible,
      previewSourceCode,
      showSourceCode,
    };
  },
});
</script>

<style lang="scss" scoped>
@import "../assets/css/md.scss";
</style>

<style lang="scss" >
pre {
  line-height: 0;
}
.Reiki-preview {
  border: 4px;
  border: 1px dashed #e7e7e7;
  span {
    font-size: 14px;
  }
  border-bottom: 1px dashed #e7e7e7;
  section {
    // padding: 12px 0;
    display: flex;
    flex-wrap: wrap;
    // justify-content: flex-start;
    button {
      margin-right: 8px;
      // margin: inherit 8px inherit inherit;
    }
  }
}

.source-code {
  max-height: 500px;
}
.language-html {
  margin: 0;
  padding: 0 15px;
}
.preview-bottom {
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px dashed #e7e7e7;
}
</style>
